import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class UserModel {
  late String name;
  // final String imgUrl = "http://b-ssl.duitang.com/uploads/item/201311/02/20131102150044_YGB5u.jpeg";
  final String imgUrl = "https://raw.githubusercontent.com/LarryLib/Resources/master/test.jpg";
  final String userAvatarUrl =
      "https://p16-tiktokcdn-com.akamaized.net/aweme/720x720/tiktok-obj/1663771856684033.jpeg";
  final String title = '呱呱的开心';
  final String description = '春日的太阳，照拂着轻风。或去爬山，或去踏青，总似那欢快的风铃';
  final String time = '2024年3月26日';
  String likeStatus = '1';

  UserModel(this.name);
}

class ImagePageView extends StatefulWidget {
  const ImagePageView({Key? key}) : super(key: key);

  @override
  State createState() => _ImagePageViewState();
}

class _ImagePageViewState extends State<ImagePageView> {
  late PageController _pageController;
  int currentPageIndex = 0;
  List<UserModel> data = [];

  @override
  void initState() {
    super.initState();
    loadData(false);

    _pageController = PageController(initialPage: 0);
    _pageController.addListener(_onPageScroll);
  }

  void _onPageScroll() {
    final pageIndex = _pageController.page?.round();
    if (pageIndex != null && pageIndex != currentPageIndex) {
      currentPageIndex = pageIndex;
      print('=========> currentPageIndex: ${currentPageIndex}');
      if (currentPageIndex == data.length - 2) {
        loadData(true);
      }
    }
  }

  /// 视频数据 API请求
  Future<void> loadData(bool isLoadMore) async {
    // 延迟200ms 模拟网络请求
    await Future.delayed(const Duration(milliseconds: 200));
    if (isLoadMore) {
      print('=========> loadData');
      List<UserModel> news = [];
      news.addAll(data);
      news.addAll(data);
      setState(() {
        data = news;
      });
    } else {
      setState(() {
        data = [
          UserModel('咕呱咕呱'),
          UserModel('咕呱咕呱1'),
          UserModel('咕呱咕呱2'),
          UserModel('咕呱咕呱3'),
          UserModel('咕呱咕呱4'),
          UserModel('咕呱咕呱5'),
          UserModel('咕呱咕呱6'),
        ];
      });
    }
  }

  @override
  void dispose() {
    _pageController.removeListener(_onPageScroll);
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var size = MediaQuery.of(context).size;
    return Scaffold(
      resizeToAvoidBottomInset: false, //很重要,不加键盘弹出视频会被挤压
      body: Stack(
        children: [
          PageView.builder(
            scrollDirection: Axis.vertical,
            itemCount: data.length,
            controller: _pageController,
            onPageChanged: (currentPage) {
              //页面发生改变的回调
            },
            itemBuilder: (context, index) {
              return ImageFullPage(
                size: size,
                model: data[index],
              );
            },
          ),
        ],
      ),
    );
  }
}

class ImageFullPage extends StatefulWidget {
  const ImageFullPage({
    Key? key,
    required this.size,
    required this.model,
  }) : super(key: key);

  final UserModel model;
  final Size size;

  @override
  State createState() => _ImageFullPageState();
}

class _ImageFullPageState extends State<ImageFullPage> {
  double imgWidth = 0;
  double imgHeight = 0;

  @override
  void initState() {
    setState(() {
      imgWidth = widget.size.width;
      imgHeight = widget.size.height;
    });
    super.initState();
  }

  ///点赞
  Future<void> onLikeClick(UserModel model) async {
    print('=====> 点击了点赞');
  }

  ///评论
  Future<void> onPrivateClick(BuildContext context, UserModel model) async {
    print('=====> 点击了私信');
    // 延迟200ms 模拟网络请求
    await Future.delayed(const Duration(milliseconds: 200));
  }

  ///观看人数
  Future<void> onCallVideoClick(UserModel model) async {
    print('=====> 点击了语音');
  }

  ///分享
  Future<void> onShareClick(UserModel model) async {
    print('=====> 点击了分享');
  }

  ///加好友
  Future<void> onAddFriendClick(UserModel model) async {
    print('=====> 点击了加好友');
  }

  ///发布人名称点击
  Future<void> onUserNameClick(UserModel model) async {
    print('=====> 点击了发布人名称');
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.grey,
      height: widget.size.height,
      width: widget.size.width,
      child: Container(
        height: widget.size.height,
        width: widget.size.width,
        decoration: const BoxDecoration(color: Colors.black),
        child: Stack(
          children: <Widget>[
            Center(
              child: imgItem(widget.model.imgUrl),
            ),
            Padding(
              padding: const EdgeInsets.only(left: 0, top: 10, bottom: 10),
              child: SafeArea(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Expanded(
                      child: Row(
                        children: <Widget>[
                          bottomPanel(
                            widget.size,
                            widget.model!,
                          ),
                          rightPanel(
                            context,
                            widget.size,
                            widget.model!,
                          )
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget bottomPanel(Size size, UserModel model) {
    return Container(
      width: size.width * 0.8,
      height: size.height,
      padding: const EdgeInsets.only(left: 15),
      decoration: const BoxDecoration(),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          GestureDetector(
            onTap: () {
              onUserNameClick(model);
            },
            child: Text(
              '@${model.name}',
              style: const TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
                fontSize: 18,
              ),
            ),
          ),
          const SizedBox(
            height: 10,
          ),
          Container(
            margin: const EdgeInsets.only(right: 30),
            child: Row(
              children: [
                Container(
                  padding: const EdgeInsets.only(
                      left: 4, right: 4, top: 2, bottom: 2),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(3.0), // 设置圆角
                    color: const Color(0xFF8B452B), // 设置背景颜色
                  ),
                  child: const Text(
                    '精',
                    style: TextStyle(
                      color: Color(0xFFF47947),
                      fontSize: 13,
                      fontWeight: FontWeight.bold,
                    ),
                    textAlign: TextAlign.center,
                  ),
                ),
                const SizedBox(
                  width: 10,
                ),
                Text(
                  model.title,
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                Text(
                  '  ·  ${model.time}',
                  style: const TextStyle(
                    color: Colors.grey,
                    fontSize: 13,
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(
            height: 5,
          ),
          Container(
            margin: const EdgeInsets.only(right: 30),
            child: Text(
              model.description,
              style: const TextStyle(
                color: Colors.white,
                fontSize: 14,
              ),
            ),
          ),
          const SizedBox(
            height: 10,
          ),
        ],
      ),
    );
  }

  Widget rightPanel(BuildContext context, Size size, UserModel model) {
    return Expanded(
      child: SizedBox(
        height: size.height,
        child: Column(
          children: <Widget>[
            Container(
              height: size.height * 0.4,
            ),
            Expanded(
                child: Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                getProfile(model),
                getLike(model, 25.0),
                getPrivateMessage(context, model, 25.0),
                getCallVideo(model, 25.0),
                const SizedBox(height: 60),
              ],
            ))
          ],
        ),
      ),
    );
  }

  Widget getLike(UserModel model, double size) {
    return GestureDetector(
      onTap: () {
        onLikeClick(model);
      },
      child: Column(
        children: <Widget>[
          Image.asset(
            'assets/ImgPageView/icon_${model.likeStatus == "1" ? '' : 'dis'}like.png',
            width: size,
            height: size,
          ),
          const SizedBox(
            height: 5,
          ),
          Text(
            '100',
            style: const TextStyle(
              color: Colors.white,
              fontSize: 12,
              fontWeight: FontWeight.w700,
            ),
          )
        ],
      ),
    );
  }

  Widget getPrivateMessage(BuildContext context, UserModel model, double size) {
    return GestureDetector(
      onTap: () {
        onPrivateClick(context, model);
      },
      child: Column(
        children: <Widget>[
          Image.asset(
            'assets/ImgPageView/icon_private_message.png',
            width: size,
            height: size,
          ),
          const SizedBox(
            height: 5,
          ),
          Text(
            '1000',
            style: const TextStyle(
              color: Colors.white,
              fontSize: 12,
              fontWeight: FontWeight.w700,
            ),
          )
        ],
      ),
    );
  }

  Widget getCallVideo(UserModel model, double size) {
    return GestureDetector(
      onTap: () {
        onCallVideoClick(model);
      },
      child: Column(
        children: <Widget>[
          Image.asset(
            'assets/ImgPageView/icon_callVideo.png',
            width: size,
            height: size,
          ),
          const SizedBox(
            height: 5,
          ),
          Text(
            '99',
            style: const TextStyle(
              color: Colors.white,
              fontSize: 12,
              fontWeight: FontWeight.w700,
            ),
          )
        ],
      ),
    );
  }

  Widget getProfile(UserModel model) {
    return GestureDetector(
      onTap: () {
        onAddFriendClick(model);
      },
      child: SizedBox(
        width: 50,
        height: 60,
        child: Stack(
          children: <Widget>[
            Container(
              width: 50,
              height: 50,
              decoration: BoxDecoration(
                  border: Border.all(color: Colors.white),
                  shape: BoxShape.circle,
                  image: DecorationImage(
                    image: NetworkImage(model.userAvatarUrl),
                    fit: BoxFit.cover,
                  )),
            ),
            Positioned(
              bottom: 3,
              left: 18,
              child: Container(
                width: 20,
                height: 20,
                decoration: const BoxDecoration(
                  shape: BoxShape.circle,
                  color: Color(0xFF69DCE5),
                ),
                child: const Center(
                  child: Icon(
                    Icons.add,
                    color: Colors.white,
                    size: 15,
                  ),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

imgItem(String imgUrl) {
  return ConstrainedBox(
    constraints: const BoxConstraints.expand(),
    child: CachedNetworkImage(
      width: double.infinity,
      height: double.infinity,
      fit: BoxFit.fill,
      imageUrl: imgUrl,
      placeholder: (context, url) => new SizedBox(
        width: 24.0,
        height: 24.0,
        child: new CircularProgressIndicator(
          strokeWidth: 2.0,
        ),
      ),
      errorWidget: (context, url, error) => new Icon(Icons.error),
    ),
  );
}
